<?php

namespace App\Http\Controllers\Car;

use App\Helpers\NewBaseData;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Car;
use App\Models\CarService;
use App\Models\CouponLog;
use Illuminate\Http\Request;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Entities\CarOrder;
use App\Models\Car\CarUsedDate;

class CarApiController extends Controller
{
    use ResponseData,NewBaseData;
    //获取列表
    public function getList(Request $request,Car $car){
        $page = $request->input('page',1);
        $size = 20;
        if($request->category){
            $data = $car->query()
                ->where('category',$request->category)
                ->where('status',1)
                ->whereNull('non_lease_time')
                ->orderBy('minimum_price','asc')
                ->get();
            $other = Car::query()
                ->where('status',1)
                ->where('category',$request->category)
                ->WhereNotNull('non_lease_time')->get();
            $data = $data->merge($other);
            $number = count($data);
            $data = $data->forPage($page,$size);
        }else{
            $data = $car->query()
                ->whereNull('non_lease_time')
                ->orderBy('minimum_price','asc')
                ->where('status',1)->get();
            $other = Car::query()
                ->where('status',1)
                ->WhereNotNull('non_lease_time')->get();
            $data = $data->merge($other);
            $number = count($data);
            $data = $data->forPage($page,$size);
        }
        // 数据返给前端显示
        $firstdate = new \DateTime($request->pre_fetch_time); // 租期开始时间
        $lastdate = new \DateTime($request->pre_return_time); // 租期结束时间
        $firstyear = $firstdate->format("Y");
        $firstmonth = $firstdate->format("m");
        $firstday = $firstdate->format("d");
        $lastyear = $lastdate->format("Y");
        $lastmonth = $lastdate->format("m");
        $lastday = $lastdate->format("d");
        $firsttime = (int)($firstyear.$firstmonth.$firstday);
        $lasttime = (int)($lastyear.$lastmonth.$lastday);
        $datelist = CarUsedDate::query()->where('time','>=',$firsttime)->where('time','<=',$lasttime)->where('is_used', 2)->pluck('car_id'); // 拿到所有已用ID
        $datelist = $datelist->unique(); // 去重
        $res =  [
            'data' => $data->values(),
            'datelist' => $datelist->values()->toArray(),
            'pagination' => [
                'total' => $number,
                'count' => count($data),
                'per_page' => $page+1,
                'current_page' => $page,
            ],
        ];
        return $this->success($res);
    }
    //获取详情
    public function getDetail(Request $request,Car $car){
        $data = $car->with('calendar')->find($request->id);
        $service = CarService::get();
        if($data&&$service){
            $data->service = $service;
            $data->coupon = $this->coupon($request->openid);
            return $this->success($data);
        }else{
            return $this->success($data);
        }

    }

    // 获取在租车辆
    public function updateCarDate(Request $request,Car $car){
        // 找到车系下的所有车辆
        $carlistall = RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('car_series_id', $request->id)->count();
        // 如果当前车系下一辆车都没有，那么这个车系都更新为不可租
        if($carlistall==0){
            CarUsedDate::query()->where('car_id', $request->id)->update(['is_used'=>2]);
            return $this->success('更新成功');
        }
        $nousedcarlist = RecognizeDrivingLicense::query()->whereNull('deleted_at')->where('car_series_id', $request->id)->where('is_used', 0)->count();
        // 找到车系下的待送达和待取回所有订单
        $orderlist = CarOrder::query()->where('car_series_id',$request->id)->where('status',5)->whereIn('process_status',[1,2])->get();
        // 找出所有订单里的起始时间点
        $starttime = '';
        $endtime = '';
        $ordertimelist = [];
        foreach ($orderlist as $k=>$order){
            $ordertimelist[$k]['car_series_id'] = $order->car_series_id;
            $ordertimelist[$k]['gear_car_id'] = $order->gear_car_id;
            if($starttime==''){
                $starttime = $order->pre_fetch_time;
            }
            if($endtime==''){
                $endtime = $order->pre_return_time;
            }
            if(empty($order->fetch_time)){
                $ordertimelist[$k]['startNum'] = (int)(date('Ymd', strtotime($order->pre_fetch_time)));
                $ordertimelist[$k]['startf'] = $order->pre_fetch_time;
                $ordertimelist[$k]['start'] = date('Y-m-d', strtotime($order->pre_fetch_time));
                if(strtotime($order->pre_fetch_time) < strtotime($starttime)){
                    $starttime = $order->pre_fetch_time;
                }
            }else{
                $ordertimelist[$k]['startNum'] = (int)(date('Ymd', strtotime($order->fetch_time)));
                $ordertimelist[$k]['startf'] = $order->fetch_time;
                $ordertimelist[$k]['start'] = date('Y-m-d', strtotime($order->fetch_time));
                if(strtotime($order->fetch_time) < strtotime($starttime)){
                    $starttime = $order->fetch_time;
                }
            }
            if(empty($order->return_time)){
                $ordertimelist[$k]['endNum'] = (int)(date('Ymd', strtotime($order->pre_return_time)));
                $ordertimelist[$k]['endf'] = $order->pre_return_time;
                $ordertimelist[$k]['end'] = date('Y-m-d', strtotime($order->pre_return_time));
                if(strtotime($order->pre_return_time) > strtotime($endtime)){
                    $endtime = $order->pre_return_time;
                }
            }else{
                $ordertimelist[$k]['endNum'] = (int)(date('Ymd', strtotime($order->return_time)));
                $ordertimelist[$k]['endf'] = $order->return_time;
                $ordertimelist[$k]['end'] = date('Y-m-d', strtotime($order->return_time));
                if(strtotime($order->return_time) > strtotime($endtime)){
                    $endtime = $order->fetch_time;
                }
            }
        }
        // 组成一个二维数组
        $carOrderList = [];
        foreach ($ordertimelist as $caritem){
            $columnValues = array_column($carOrderList, 'gear_car_id'); // 获取所有的值
            $keys = array_search($caritem['gear_car_id'], $columnValues);
            if($keys !== false){
                $carOrderList[$keys]['timelist'][] = [
                    'startNum'=>$caritem['startNum'],
                    'endNum'=>$caritem['endNum']
                ];
            }else{
                $carOrderList[] = [
                    'gear_car_id'=>$caritem['gear_car_id'],
                    'timelist'=>[
                        [
                            'startNum'=>$caritem['startNum'],
                            'endNum'=>$caritem['endNum']
                        ]
                    ]
                ];
            }
        }
        info($carOrderList);
        info($ordertimelist);
        // return $this->success($ordertimelist);
        info('$starttime'.$starttime);
        info('$endtime'.$endtime);
        // 根据时间阶段，找出当前车系下的日节点
        $firstdate = new \DateTime($starttime);
        $lastdate = new \DateTime($endtime);
        $firstyear = $lastdate->format("Y");
        $firstmonth = $firstdate->format("m");
        $firstday = $firstdate->format("d");
        $lastyear = $lastdate->format("Y");
        $lastmonth = $lastdate->format("m");
        $lastday = $lastdate->format("d");
        $firsttime = (int)($firstyear.$firstmonth.$firstday);
        $lasttime = (int)($lastyear.$lastmonth.$lastday);
        $datelist = CarUsedDate::query()->where('car_id',$request->id)->where('time','>=',$firsttime)->where('time','<=',$lasttime)->get();
        // return $this->success($datelist);
        $gear_car_ids = array_column($ordertimelist, 'gear_car_id');
        $gear_car_ids = array_unique($gear_car_ids); // 去重
        // return $this->success(count($gear_car_ids));
        $datelogids = [];
        // nousedcarlist待租车辆为0时，才需要更新是否已租空，如果还有待租车辆>0，那么车系就是可租的，不用显示为已租空
        if(count($datelist)>0&&$nousedcarlist==0){
            foreach ($datelist as $item){
                $itmtime = strtotime($item->year.'-'.$item->month.'-'.$item->day); // 当前日期时间戳
                // 如果只有一辆车
                if(count($gear_car_ids)==1){
                    foreach ($ordertimelist as $orderitem){
                        if($itmtime>=strtotime($orderitem['start'])&&$itmtime<=strtotime($orderitem['end'])){
                            $datelogids[]=$item->id;
                        }
                    }
                }elseif(count($gear_car_ids)>1){
                    // 大于一辆车，取出所有已使用天数，找出相同时间的日期，才算已租
                    $dateItemlist = [];
                    foreach ($carOrderList as $carorderitem){
                        $dateItemlist[] = $this->array_is_in($carorderitem['timelist'],$item->time);
                    }
                    // info($dateItemlist);
                    // info(count($dateItemlist).'---'.count(array_unique($dateItemlist)));
                    if (count(array_unique($dateItemlist))==1) {
                        $datelogids[]=$item->id;
                    }
                }
                // // 如果这条记录的年月日，都包含在了订单里，那么就更新当天为已使用(时分秒逻辑目前暂不支持)
                // if($this->isHaveValue($ordertimelist,$item)){
                //     $datelogids[]=$item->id;
                // }
            }
        }
        // return $this->success($datelogids);
        // 先把当天之后的日历都更新为可租。再根据订单更新为不可租
        // $yearnow = date('Y');
        // $monthnow = date('m');
        // $daynow = date('d');
        // // CarUsedDate::query()->where('year',$yearnow)->where('month','>=',$monthnow)->where('day','>=',$daynow)->update(['is_used'=>1]);
        // CarUsedDate::query()->where(function ($query) use($request,$yearnow,$monthnow) {
        //     $query->where('car_id',$request->id)->where('year',$yearnow)->where('month','>',$monthnow);
        // })->orWhere(function ($query) use($request,$monthnow,$yearnow,$daynow) {
        //     $query->where('car_id',$request->id)->where('year',$yearnow)->where('month',$monthnow)->where('day','>=',$daynow);
        // })->update(['is_used'=>1]);
        CarUsedDate::query()->where('car_id',$request->id)->where('time','>=',$firsttime)->where('time','<=',$lasttime)->update(['is_used'=>1]);
        if(count($datelogids)>0){
            CarUsedDate::query()->whereIn('id', $datelogids)->update(['is_used'=>2]);
        }
        return $this->success('更新成功');
    }
    // 给定一个数组和一个值，判断是否在里面
    protected function array_is_in($array, $values) {
        $isin = "";
        foreach ($array as $value) {
            // 只要有一个满足，就是true
            if ($value['startNum']<=$values&&$value['endNum']>=$values) {
                $isin = $values;
            }
        }
        return $isin;
    }
    //判断包含关系
    protected function isHaveValue($list,$itm){
        $istrue = true;
        $itmtime = strtotime($itm->year.'-'.$itm->month.'-'.$itm->day); // 当前日期时间戳
        // 找到所有订单的共同时间段
        foreach ($list as $listitem){
            // 如果车系日历在任意一个之外，就是false
            if($itmtime < strtotime($listitem['start'])||$itmtime > strtotime($listitem['end'])){
                $istrue = false;
            }
        }
        return $istrue;
    }

}
